package com.currency.util;

import cn.hutool.http.HttpUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import org.apache.commons.codec.digest.DigestUtils;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.currency.exception.AppException;
import com.currency.interceptor.ParamInterceptor;

import java.text.DecimalFormat;
import java.util.UUID;

public class PayUtil {
    private static final Log log = LogFactory.get(ParamInterceptor.class);
    private static final String appId = "2021001154650303";
    // private static final String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCyPEbc/M64rn5Orl72tuIGe6QOvI2DCfGG1fH5Ig1OGIzOcwV5Pqb9P5WiZY4JYHdmUd+NZ7cHh9aXbnNQIuPuGlcYMfesuNzLXs7xc+8lGeNXWSSvIf/PwrPym8KmTiRIN7jM8OSJQ6pUicJIXCxAdbWrTbcAO464UfaLXcn08pWf5FgK5Wmc0MJBQ1/Wv6J+OhcfdxEsB5ffBoLWZYe5tajcI+1pL9BNtxddc7bPkgIyot/AnYJaex4S0NYyUQuCp2tnFCwUGIeSlxzx4VahvQ80+6T0mUurTY3vZYVJjpV1+RpAB3IFZnGlwkGMpP3hYiytwI4C5aHtv+NI2lgnAgMBAAECggEAF2OBiQ5Dskhzmq+XFpj5IBCpfqWPjFqJrz/z+NVXGaBvGchON5LZJvJpGF5rPR/Di1HDHDM3+W0B4+1ChImPj3c1Zp9n+OppTuaqEVU9VIkJJDU2cyTrBMBwDK4T5O7sI+3r+jjCRKD0gRN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publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsjxG3PzOuK5+Tq5e9rbiBnukDryNgwnxhtXx+SINThiMznMFeT6m/T+VomWOCWB3ZlHfjWe3B4fWl25zUCLj7hpXGDH3rLjcy17O8XPvJRnjV1kkryH/z8Kz8pvCpk4kSDe4zPDkiUOqVInCSFwsQHW1q023ADuOuFH2i13J9PKVn+RYCuVpnNDCQUNf1r+ifjoXH3cRLAeX3waC1mWHubWo3CPtaS/QTbcXXXO2z5ICMqLfwJ2CWnseEtDWMlELgqdrZxQsFBiHkpcc8eFWob0PNPuk9JlLq02N72WFSY6VdfkaQAdyBWZxpcJBjKT94WIsrcCOAuWh7b/jSNpYJwIDAQAB";
    private static final String aliPayPubKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnuKhbQBjul8WKTGzDyczkPKXBPJNFf80B1pvqApAgrSH7QO3uPkbCU/FpKWVAP9Sqr9KCVejEB/p3VuktDxDKTLPqwnj7SGxxOXFvwSYBdrWr66XwSyzs6Xi7m8x8NZpZQcLb8wHm6Y8dNsTt98hSeVIf1wxWXunFAhjnBjW0BFrR+6Yh50GEDH5JTue2s39bB7a23KrwqHOrDkL/OO+qDKvl9ugk/cqmmcqOyGI4v9UODt2DI3qUsd66IuDXqFMpy6dJbELvRBHI4NLyBG4PdZmVBMDaZ1ahOA9PgMstTxblaxN0myGHpDKxH48xsQncTQSAsfRT9KKYNf9Uugx+QIDAQAB";

    private static final String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCTdbtIAEf/650DHMTH87uM12Up1qNp9gCntJExEFuU+EmOX5HMsj753rie3M14itRQ1AfF2mErzaGTIUvZKxtPxl1tODbOr+btQscvb+lnAFPPKNnybTUNsb6Cv00anX37wj8o0MpZDiJhcrkMDoo3xwhC8ZvTBdpAzvpuQhsSBU/ZhpdXwn7DYPOLxpxa6aGAgdzSUu8/z1RB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YOJwFy3RSKXPQDMnkFPqvrfq3RjkD7tm4r/yUUDaD2mpzrBMZt0XnaPwcisViIx7ox1ot0gT1zSowDxZCQ/lWUGuO2utj4q7PcipFYdboEm7AfYPYwwKBgBstDhxlJk8aNw9NJxnC8w7TVwbdtqSxs+Htx8nCw7nWHWCsoeSXR1No1RNE4z1AIln0VL1Q7ToAQc0CYCiBWIJm1YMXR9GsLnzj00J4R3bEWBuL4weh3EF9gj8QXARvbUJw64YlmWXQTpjnUQJUiLFWNIBIp0+CwOohclWlVnO8";
    private static final String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk3W7SABH/+udAxzEx/O7jNdlKdajafYAp7SRMRBblPhJjl+RzLI++d64ntzNeIrUUNQHxdphK82hkyFL2SsbT8ZdbTg2zq/m7ULHL2/pZwBTzyjZ8m01DbG+gr9NGp19+8I/KNDKWQ4iYXK5DA6KN8cIQvGb0wXaQM76bkIbEgVP2YaXV8J+w2Dzi8acWumhgIHc0lLvP89UQb/WQh2t37ermW9A1lNheARMbLL4ows6fRa9D9z1pJZl6NBSChK+WkBs+MSwdoExXpZtVyIwZrDsaz8sm0Jsj2EMARkhZbHpQPn5yNbyRqZtiKBu+2Oe5Qxv/E3m5UOgKirkiRSc7QIDAQAB";

    public static final String appid = "wx910deb30bf41ba3a";
    public static final String appSecret = "437a9758e6c8f52f49cca02b533f4fdb";
    public static final String mch_id = "1584805601";


    public static AlipayTradeAppPayResponse postFroLipayNew(String payId, int amount, String appCertPath, String alipayCertPath, String alipayRootCertPath) throws Exception {
        //构造client
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        //设置网关地址
        certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
        //设置应用Id
        certAlipayRequest.setAppId(appId);
        //设置应用私钥
        certAlipayRequest.setPrivateKey(privateKey);
        //设置请求格式，固定值json
        certAlipayRequest.setFormat("json");
        //设置字符集
        certAlipayRequest.setCharset("utf-8");
        //设置签名类型
        certAlipayRequest.setSignType("RSA2");
        //设置应用公钥证书路径
        certAlipayRequest.setCertPath(appCertPath);
        //设置支付宝公钥证书路径
        certAlipayRequest.setAlipayPublicCertPath(alipayCertPath);
        //设置支付宝根证书路径
        certAlipayRequest.setRootCertPath(alipayRootCertPath);
        //构造client
        AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        model.setBody("金币购买");
        model.setSubject("物流APP金币");

        model.setOutTradeNo(payId);
        model.setTimeoutExpress("30m");
        model.setTotalAmount(getYuanAmountForStr(amount));
        model.setProductCode("Gold001");
        request.setBizModel(model);
        //request.setNotifyUrl("商户外网可以访问的异步地址");
        AlipayTradeAppPayResponse response = null;
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            response = alipayClient.sdkExecute(request);
            log.info("支付宝支付返回结果为：" + JSONObject.toJSONString(response));
        } catch (AlipayApiException e) {
            throw new AppException("cy1001", "外部支付出现异常");
        }
        return response;
    }

    public static AlipayTradeAppPayResponse postForAliPay(String payId, int amount) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient
                ("https://openapi.alipay.com/gateway.do", appId, privateKey, "json",
                        "utf-8", aliPayPubKey, "RSA2");
//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
//SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody("物流APP金币购买");
        model.setSubject("物流APP金币");

        model.setOutTradeNo(payId);
        model.setTimeoutExpress("30m");
        model.setTotalAmount(getYuanAmountForStr(amount));
        model.setProductCode("Gold001");
        request.setBizModel(model);
        //request.setNotifyUrl("商户外网可以访问的异步地址");
        AlipayTradeAppPayResponse response = null;
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            response = alipayClient.sdkExecute(request);
            log.info("支付宝支付返回结果为：" + JSONObject.toJSONString(response));
        } catch (AlipayApiException e) {
            throw new AppException("cy1001", "外部支付出现异常");
        }
        return response;
    }

    public static AlipayTradeQueryResponse postForAliPayOrderInfo(String payId, String appCertPath, String alipayCertPath, String alipayRootCertPath) throws Exception {
        //AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appId, privateKey, "json", "utf-8", aliPayPubKey, "RSA2");
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        //设置网关地址
        certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
        //设置应用Id
        certAlipayRequest.setAppId(appId);
        //设置应用私钥
        certAlipayRequest.setPrivateKey(privateKey);
        //设置请求格式，固定值json
        certAlipayRequest.setFormat("json");
        //设置字符集
        certAlipayRequest.setCharset("utf-8");
        //设置签名类型
        certAlipayRequest.setSignType("RSA2");
        //设置应用公钥证书路径
        certAlipayRequest.setCertPath(appCertPath);
        //设置支付宝公钥证书路径
        certAlipayRequest.setAlipayPublicCertPath(alipayCertPath);
        //设置支付宝根证书路径
        certAlipayRequest.setRootCertPath(alipayRootCertPath);
        AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" + "\"out_trade_no\":\"" + payId + "\"}");
        AlipayTradeQueryResponse response = alipayClient.certificateExecute(request);
        log.info("查询订单返回结果为：" + JSONObject.toJSONString(response));
        return response;
    }

    public static void getAlipayUserId(String token) {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appId, privateKey, "json", "UTF8", aliPayPubKey, "RSA2");
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setCode(token);
        request.setGrantType("authorization_code");
        try {
            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
            System.out.println(oauthTokenResponse.getAccessToken());
            System.out.println(oauthTokenResponse.getUserId());
        } catch (AlipayApiException e) {
            //处理异常
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        postForAliPayOrderInfo("Pay1333340568918429696","D:\\soft\\WXCertUtil\\WXCertUtil\\cert\\appCertPublicKey_2021001154650303.crt", "D:\\soft\\WXCertUtil\\WXCertUtil\\cert\\alipayCertPublicKey_RSA2.crt", "D:\\soft\\WXCertUtil\\WXCertUtil\\cert\\alipayRootCert.crt");
        //postForAliPay("11111111", 1);
        // postForAliPay("1111", 1);
        // getAlipayUserId("0d72c0d8487b4b59b25d376e9486OF35");
    }

    public static String postForWX(String payId, int amount) throws AppException {

        UUID uuid = UUID.randomUUID();
        //随机字符串
        String nonce_str = uuid.toString().replace("-", "");

        String body = "金币充值";
        String out_trade_no = payId;
        String total_fee = amount + "";
        String spbill_create_ip = "156.135.157.150";
        String notify_url = "http://47.105.177.145:18802/";
        String trade_type = "APP";

        StringBuffer allParam = new StringBuffer();
        allParam.append("appid=" + appid + "&");
        allParam.append("body=" + body + "&");
        allParam.append("mch_id=" + mch_id + "&");
        allParam.append("nonce_str=" + nonce_str + "&");
        allParam.append("notify_url=" + notify_url + "&");
        allParam.append("out_trade_no=" + out_trade_no + "&");
        allParam.append("spbill_create_ip=" + spbill_create_ip + "&");
        allParam.append("total_fee=" + total_fee + "&");
        allParam.append("trade_type=" + trade_type);

        System.out.println(allParam);
        // 签名生成算法
        String sign = DigestUtils.md5Hex(allParam.toString() + "&key=b534811e05584cff8593237757dad7a2");
        System.out.println(sign);

        StringBuffer payParam = new StringBuffer();
        payParam.append("<xml>");
        payParam.append("<appid>" + appid + "</appid>");
        payParam.append("<body>").append(body).append("</body>");
        payParam.append("<mch_id>" + mch_id + "</mch_id>");
        payParam.append("<nonce_str>").append(nonce_str).append("</nonce_str>");
        payParam.append("<notify_url>").append(notify_url).append("</notify_url>");
        payParam.append("<out_trade_no>").append(out_trade_no).append("</out_trade_no>");
        payParam.append("<spbill_create_ip>").append(spbill_create_ip).append("</spbill_create_ip>");
        payParam.append("<total_fee>").append(total_fee).append("</total_fee>");
        payParam.append("<trade_type>").append(trade_type).append("</trade_type>");
        payParam.append("<sign>").append(sign).append("</sign>");
        payParam.append("</xml>");

        log.info(payParam.toString());
        String ans = HttpUtil.post("https://api.mch.weixin.qq.com/pay/unifiedorder", payParam.toString());

        log.info(ans);
        JSONObject json;
        try {
            json = XmlToJson.xml2Json(ans);
            log.info(json.toJSONString());
        } catch (Exception e) {
            log.warn("转换xml时，出现异常");
            e.printStackTrace();
            throw new AppException("cy9992", "微信支付网络出现异常");
        }

        return json.toString();
    }


    public static String getYuanAmountForStr(int amount) throws Exception {
        if (amount <= 0) {
            throw new AppException("cy9998", "金额不能小于等于0");
        }
        String str = amount + "";
        if (str.length() == 1) {
            str = "0.0" + str;
        } else if (str.length() == 2) {
            str = "0." + str;
        } else {
            str = str.substring(0, str.length() - 2) + "." + str.substring(str.length() - 2);
        }
        return str;
    }

    public static String yuanToFen(String yuanAmount) throws Exception {
        //去掉 ,
        yuanAmount = yuanAmount.replace(",", "");
        DecimalFormat df = new DecimalFormat("#");
        return df.format(Double.parseDouble(yuanAmount) * 100);
    }
}
